package fun.linze.wallpaperwebsite.controller;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/files")
public class FileController {
    @Value("${wallpaper.upload.dir}")
    private String uploadDir;
    @Value("${wallpaper.thumbnail.dir}")
    private String thumbnailDir;
    //上传壁纸
    @PostMapping("/upload")
    public ResponseEntity<?> uploadWallpaper(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        // 1. 获取原始文件名和后缀
        String originalFilename = file.getOriginalFilename();
        String ext = StringUtils.getFilenameExtension(originalFilename);
        // 2. 生成唯一文件名
        String newFileName = UUID.randomUUID().toString() + (ext != null ? "." + ext : "");
        // 3. 设置存储路径
        File dest = new File(uploadDir + newFileName);
        dest.getParentFile().mkdirs();
        try {
            file.transferTo(Paths.get(uploadDir, newFileName));
            // 生成缩略图
            File thumbnailDest = Paths.get(thumbnailDir, newFileName).toFile();
            thumbnailDest.getParentFile().mkdirs();
            Thumbnails.of(Paths.get(uploadDir, newFileName).toFile()).size(320, 180).toFile(thumbnailDest);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件保存失败");
        }
        // 4. 返自定义响应
        Map<String, String> result = new HashMap<>();
        result.put("fileName", newFileName);
        return ResponseEntity.ok(result);
    }

    //下载壁纸
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadWallpaper(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取缩略图
    @GetMapping("/thumbnail/{fileName:.+}")
    public ResponseEntity<Resource> getThumbnail(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(thumbnailDir).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok().body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }

}
